package com.appheader.rongmaphone;

import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.appheader.rongmaphone.activity.MySettingActivity;
import com.appheader.rongmaphone.activity.ScanActivity;
import com.appheader.rongmaphone.cache.preference.PreferenceUtil;
import com.appheader.rongmaphone.entity.Project;
import com.appheader.rongmaphone.fragment.CloudFragment;
import com.appheader.rongmaphone.fragment.OffLineFragment;
import com.appheader.rongmaphone.user.UserInfo;
import com.appheader.rongmaphone.utils.json.JSONUtil;
import com.appheader.rongmaphone.utils.network.HttpUtil;
import com.zxing.activity.CaptureActivity;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.litepal.crud.DataSupport;

import java.io.IOException;
import java.math.BigDecimal;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity implements View.OnClickListener, ViewPager.OnPageChangeListener {

    private FragmentManager manager;
    private CloudFragment cloudFragment, cloudFragment1;
    private OffLineFragment offLineFragment;
    private ViewPager viewPager;
    private boolean isCloudMove = true;//动画执行判断
    private boolean isoffLineMove = true;
    private List<Fragment> fragmentList;
    private ImageView homeMyImg, scanImg;//底部个人中心按钮和扫描按钮
    private ImageView refreshImg;//刷新按钮
    private boolean isreFresh = true;//是否刷新

    private String TAG = "MainActivity";
    private TextView cloudSchemeText, offLineText;//云方案，离线缓存
    private final static int REQUEST_CODE = 0;
    private ImageView imageTower, imageSun;//塔,日出
    private RelativeLayout relativeLayout, off_line_scroll_content_layout;//条幅

    private RelativeLayout off_line_head_layout, clound_head_layout;
    private ImageView scrollImg;
    private ImageView cloud_scroll_img;
    private FrameLayout frameLayout;
    private TextView wifiContent;
    private TextView useNumContent;
    private PreferenceUtil preferenceUtil;
    private TextView offLineContent;
    private TextView offLineUseNumContent;

    private static double space = 0.0;
    private static int totalProject = 0;
    private static int currentProject = 0;
    private double offLineSpace;
    private String uid;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getSupportActionBar().hide();
        setContentView(R.layout.activity_main);
        //测试popupwindow
//        initPop();
        initView();
        preferenceUtil = new PreferenceUtil(getApplicationContext());
        getUserListData();
        //刚进来第一页先加载
        manager = getSupportFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();
        hideFragment(transaction);
        transaction.commit();

        initViewPager();
        initTextViewListener();
        //必须执行这句才能获取到sessionID
//        HttpHeader.getHeaderRequest("",null,this);
    }

    private void getUserListData() {
        HttpUtil.getCloudUserListOkHttpClient(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String respon = response.body().string();
                Log.e("CloudFragment", "onResponse: " + respon);
                try {
                    JSONObject jsonObject = new JSONObject(respon);
                    JSONObject jsonObject1 = jsonObject.getJSONObject("data");
                    JSONObject jsonObject2 = jsonObject1.getJSONObject("versionInfo");
                    final String space = jsonObject2.getString("space");
                    String usedSpace = jsonObject2.getString("usedSpace");
                    final int rongyu = jsonObject2.getInt("rongyu");
                    double surplus;
                    if (usedSpace.equals("0")) {
                        surplus = (double) (Double.valueOf(space) - 0) / 1024;
                    }else {
                        surplus = (double) (Double.valueOf(space) - Double.valueOf(usedSpace)) / 1024;
                    }
                    BigDecimal bg = new BigDecimal(surplus);
                    //保留小数点后两位
                    final double result = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                    Log.e("FROMAT", "onResponse: " + result + "GB");
//                    offLineSpace = result;
                    String userList = preferenceUtil.getString("userList");
                    String userStr = preferenceUtil.getString("userStr");//从私有目录取出
                    Log.e(TAG, "onResponse:userStr "+userStr );
                    UserInfo userInfo = JSONUtil.userInfos(userStr);
                    uid = userInfo.getUid();
                    JSONObject userJsonObjectt = new JSONObject(userList);
                    JSONObject userJsonObject1 = userJsonObjectt.getJSONObject("data");
                    JSONArray jsonArray = userJsonObject1.getJSONArray("list");
                    final int totalProjectNum = jsonArray.length();
                    //下载的方案个数从数据库中取
                    List<Project> projectList = DataSupport.findAll(Project.class);
                    int moban=0;
                    for (int i = 0; i < projectList.size(); i++) {
                        String dbUid = projectList.get(i).getCreator();
                        if (dbUid.equals(uid)){
                            moban++;
                        }
                    }
                    final int currentProjectNum = moban;
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            cloudSchemeText.setText("云方案 ("+totalProjectNum+")");
                            offLineText.setText("离线缓存 ("+currentProjectNum+")");
                            if (result<1&&result>0){
                                wifiContent.setText(Double.valueOf(space)+"MB");
                                offLineContent.setText(Double.valueOf(space)+"MB");
                            }else {
                                wifiContent.setText(result + "GB");
                                offLineContent.setText(result + "GB");
                            }

                            useNumContent.setText(rongyu+"");
                            offLineUseNumContent.setText(rongyu+"");
                        }
                    });
//
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }
    private void initViewPager() {
        fragmentList = new ArrayList<>();
        //TODO 云方案直接网络请求，离线缓存加载本地数据
        cloudFragment = new CloudFragment();
        offLineFragment = new OffLineFragment();

        //offLineFragment加载本地缓存的数据
        fragmentList.add(cloudFragment);
        fragmentList.add(offLineFragment);

        viewPager.setAdapter(new HomePagerAdapter(getSupportFragmentManager(), fragmentList));
        viewPager.setCurrentItem(0);
        //设置viewPager监听
        viewPager.addOnPageChangeListener(this);
    }

    private void hideFragment(FragmentTransaction transaction) {
        if (cloudFragment != null) {
            transaction.hide(cloudFragment);
        }
        if (offLineFragment != null) {
            transaction.hide(offLineFragment);
        }
    }

    private void initTextViewListener() {
        //刚开始时加载云方案
        cloudSchemeText.setBackground(getResources().getDrawable(R.drawable.yello_shape));
        cloudSchemeText.setTextColor(getResources().getColor(R.color.tabWhite));
        offLineText.setBackground(getResources().getDrawable(R.drawable.rb_shape));
        offLineText.setTextColor(getResources().getColor(R.color.deep_search_selected));
        cloudSchemeText.setOnClickListener(new textViewListener(0));
        offLineText.setOnClickListener(new textViewListener(1));
    }

    //点击监听事件
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.home_my_img://跳转到个人中心页面,
                //TODO
                Intent intent = new Intent(MainActivity.this, MySettingActivity.class);
                startActivity(intent);
                break;
            case R.id.home_scan_img://跳转到扫描状态
                Intent scanIntent = new Intent(MainActivity.this, CaptureActivity.class);
                startActivityForResult(scanIntent, REQUEST_CODE);
                break;
            case R.id.refresh_img://刷新按钮监听
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                manager = getSupportFragmentManager();
                FragmentTransaction transaction = manager.beginTransaction();
//                hideFragment(transaction);
                showFragment(transaction);
                transaction.commit();
                break;
        }
    }

    private void showFragment(FragmentTransaction transaction) {
        if (cloudFragment != null) {
            transaction.show(cloudFragment);
        } else {
            cloudFragment = new CloudFragment();
            transaction.add(R.id.home_viewpager, cloudFragment).show(cloudFragment);
        }
    }


    //三个翻页监听事件
    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        AnimatorSet animatorSet = new AnimatorSet();

        if (position == 0) {
            cloudSchemeText.setTextColor(Color.parseColor("#ffffff"));
            cloudSchemeText.setBackground(getResources().getDrawable(R.drawable.yello_shape));
            offLineText.setTextColor(getResources().getColor(R.color.deep_search_selected));
            offLineText.setBackground(getResources().getDrawable(R.drawable.rb_shape));

            off_line_head_layout.setVisibility(View.INVISIBLE);
            clound_head_layout.setVisibility(View.VISIBLE);
        } else if (position == 1) {
            cloudSchemeText.setTextColor(getResources().getColor(R.color.deep_search_selected));
            cloudSchemeText.setBackground(getResources().getDrawable(R.drawable.rb_shape));
            offLineText.setTextColor(Color.parseColor("#ffffff"));
            offLineText.setBackground(getResources().getDrawable(R.drawable.yello_shape));

            clound_head_layout.setVisibility(View.INVISIBLE);
            off_line_head_layout.setVisibility(View.VISIBLE);

            if (isoffLineMove) {
                animatorView(animatorSet);
                isoffLineMove = false;
            }
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);

    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    class textViewListener implements View.OnClickListener {

        private int index = 0;

        public textViewListener(int i) {
            index = i;
        }

        @Override
        public void onClick(View v) {
            AnimatorSet animatorSet = new AnimatorSet();
            viewPager.setCurrentItem(index);
            if (cloudSchemeText.isPressed()) {//云方案的动画
                cloudSchemeText.setBackground(getResources().getDrawable(R.drawable.yello_shape));
                cloudSchemeText.setTextColor(getResources().getColor(R.color.tabWhite));

                off_line_head_layout.setVisibility(View.INVISIBLE);
                clound_head_layout.setVisibility(View.VISIBLE);
//                cloudAnimatorView();

            } else if (offLineText.isPressed()) {//离线缓存的动画
                offLineText.setBackground(getResources().getDrawable(R.drawable.yello_shape));
                offLineText.setTextColor(getResources().getColor(R.color.tabWhite));
                clound_head_layout.setVisibility(View.INVISIBLE);
                off_line_head_layout.setVisibility(View.VISIBLE);
//                offLineContent.setText(offLineSpace+"GB");

                if (isoffLineMove) {
                    animatorView(animatorSet);
                    isoffLineMove = false;
                }

            }
        }
    }

    private void initView() {
        cloudSchemeText = (TextView) findViewById(R.id.clound_text);
        offLineText = (TextView) findViewById(R.id.offline_text);
        wifiContent = (TextView) findViewById(R.id.wifi_content);//
        useNumContent = (TextView) findViewById(R.id.use_num_content);
        offLineContent = (TextView) findViewById(R.id.off_line_wifi_content);
        offLineUseNumContent = (TextView) findViewById(R.id.off_line_use_num_content);
        viewPager = (ViewPager) findViewById(R.id.home_viewpager);
        homeMyImg = (ImageView) findViewById(R.id.home_my_img);
        scanImg = (ImageView) findViewById(R.id.home_scan_img);
        refreshImg = (ImageView) findViewById(R.id.refresh_img);
        imageSun = (ImageView) findViewById(R.id.clound_img);
        imageTower = (ImageView) findViewById(R.id.tower_img);
        relativeLayout = (RelativeLayout) findViewById(R.id.scroll_content_layout);
        scrollImg = (ImageView) findViewById(R.id.scroll_img);
        cloud_scroll_img = (ImageView) findViewById(R.id.cloud_scroll_img);
        off_line_scroll_content_layout = (RelativeLayout) findViewById(R.id.off_line_scroll_content_layout);
        off_line_head_layout = (RelativeLayout) findViewById(R.id.off_line_head_layout);
        clound_head_layout = (RelativeLayout) findViewById(R.id.clound_head_layout);
        frameLayout = (FrameLayout) findViewById(R.id.scroll_layout);
        homeMyImg.setOnClickListener(this);
        scanImg.setOnClickListener(this);
        refreshImg.setOnClickListener(this);

    }

    //内部类，继承自FragmentPagerAdapter
    class HomePagerAdapter extends FragmentPagerAdapter {
        private List<Fragment> list;

        public HomePagerAdapter(FragmentManager fm, List<Fragment> list) {
            super(fm);
            this.list = list;
        }

        @Override
        public Fragment getItem(int position) {
            return list.get(position);
        }

        @Override
        public int getCount() {
            return list.size();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.e(TAG, "onResume: ----------------");
    }

    //设置动画
    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);

//        animatorView();//首页顶部离线的动画
        AnimatorSet animatorSet = new AnimatorSet();
        if (isCloudMove) {
            cloudAnimatorView(animatorSet);//首页顶部云方案的动画
            isCloudMove = false;
        }
    }

    //云方案动画
    private void cloudAnimatorView(AnimatorSet animatorSet) {
//         = new AnimatorSet();
        //获取屏幕的宽度getWindow().getWindowManager().getDefaultDisplay().getWidth()
        ObjectAnimator animator3 = ObjectAnimator.ofFloat(off_line_scroll_content_layout,
                "translationX",
                -getWindow().getWindowManager().getDefaultDisplay().getWidth()
//                frameLayout.getWidth()
                        + imageSun.getWidth() + cloud_scroll_img.getWidth(), 0);//-(relativeLayout.getWidth()-imageTower.getWidth())
        animatorSet.setDuration(2000);
        ObjectAnimator animator5 = ObjectAnimator.ofFloat(cloud_scroll_img,
                "translationX", 0,
//                getWindow().getWindowManager().getDefaultDisplay().getWidth()
                frameLayout.getWidth()
                        - imageSun.getWidth());//-(relativeLayout.getWidth()-imageTower.getWidth())
        animatorSet.playTogether(animator3, animator5);
        animatorSet.start();
    }

    //离线缓存动画
    private void animatorView(AnimatorSet animatorSet) {
        //获取屏幕的宽度getWindow().getWindowManager().getDefaultDisplay().getWidth()
        ObjectAnimator animator3 = ObjectAnimator.ofFloat(relativeLayout,
                "translationX",
                -getWindow().getWindowManager().getDefaultDisplay().getWidth()
                        + imageTower.getWidth() + scrollImg.getWidth(), 0);
        animatorSet.setDuration(2000);
        ObjectAnimator animator5 = ObjectAnimator.ofFloat(scrollImg,
                "translationX", 0,
//以包裹布局的宽度为标准
                frameLayout.getWidth() - imageTower.getWidth());
        animatorSet.playTogether(animator3, animator5);
        animatorSet.start();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
            //这个result是给定的不能随便写
            String result = data.getExtras().getString("result");
            if (!TextUtils.isEmpty(result)) {
                Log.i("AAAAA", "" + result);
                String urlHost = "";
                try {
                    urlHost = new URL(result).getHost();
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                }
                Log.e("getHost", "onActivityResult: ----" + urlHost);
                if (urlHost.equals("www.armyhorse.com")) {
                    //如果与本公司域名相同，则进入详情下载页面
                    Log.e("--getHost", "onActivityResult: ----" + urlHost);
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    Intent intent = new Intent(MainActivity.this, ScanActivity.class);
                    intent.putExtra("result", result);
                    startActivity(intent);
                } else {
                    //不同，则提示二维码无效
                    Toast.makeText(MainActivity.this, "获取无效", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.e(TAG, "onStart: ------------------");
    }
    @Override
    protected void onPause() {
        super.onPause();
        Log.e(TAG, "onPause: ------------------");
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        Log.e(TAG, "onRestart: -----------------");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.e(TAG, "onDestroy: ------------------");
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.e(TAG, "onStop: ");
    }
}
